﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using JohnnySins.DAL;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;
using JohnnySins.Code;

namespace JohnnySins.Admin
{
    public partial class MyVideos : System.Web.UI.Page
    {
        public string JsCodeToRunOnReady { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            FindSelected();

            if (!IsPostBack)
            {
                LoadMyVideo();
            }
        }
        public int[] Selected { get; set; }

        private void FindSelected()
        {
            var selected = new List<int>();

            foreach (GridViewRow row in grid.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var check = row.Cells[0].FindControl("cbSelected") as CheckBox;
                    if (check.Checked)
                    {
                        var id = row.FindControl("hidId") as HiddenField;
                        selected.Add(int.Parse(id.Value));
                    }
                }
            }

            Selected = selected.ToArray();
        }

        protected IEnumerable<MyVideo> MyVideoList()
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                bool? isPublic = null;
                bool? isFitness = null;

                if (ddlIsPublicFilter.SelectedValue == "1")
                    isPublic = true;
                else if (ddlIsPublicFilter.SelectedValue == "0")
                    isPublic = false;

                if (ddlIsFitnessFilter.SelectedValue == "1")
                    isFitness = true;
                else if (ddlIsFitnessFilter.SelectedValue == "0")
                    isFitness = false;

                return repo.FindAll(isPublic, isFitness);
            }
        }

        protected void LoadMyVideo()
        {
            grid.DataSource = MyVideoList();
            grid.DataBind();
        }

        protected void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                MyVideo item = (MyVideo)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("btnDeactivate");
                ibtn.Visible = item.IsActive;

                ibtn = (ImageButton)e.Row.FindControl("btnActivate");
                ibtn.Visible = !item.IsActive;

                CheckBox cbSelected = (CheckBox)e.Row.FindControl("cbSelected");
                cbSelected.Checked = Selected.Contains(item.MyVideoId);
            }

            if (e.Row.RowType == DataControlRowType.Header)
            {
                CheckBox chbAll = (CheckBox)e.Row.FindControl("chbAll");
                chbAll.Checked = (Selected.Length == (grid.DataSource as IEnumerable<MyVideo>).Count());
            }
        }

        protected void grid_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            if (e.CommandName == "delete")
            {
                DeleteMyVideo(id);
            }
            else
            {
                using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
                {
                    switch (e.CommandName)
                    {
                        case "deactivate":
                            repo.Deactivate(id);
                            break;
                        case "activate":
                            repo.Activate(id);
                            break;
                    }
                }
            }

            LoadMyVideo();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadMyVideo();
        }

        protected void upDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upDetails.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdId.Text = Request["__EVENTARGUMENT"];


                fuMyVideoFileName.Clear();
                fuHDQTFileName.Clear();
                fuHDWinFileName.Clear();
                fuLDQTFileName.Clear();
                fuLDWinFileName.Clear();
                fuPoster.Style.Clear();
                
                if (hdId.Text != "-1")
                {
                    using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
                    {
                        lblDialogTitle.Text = "EDIT MY VIDEO";
                        MyVideo itm = repo.Find(Convert.ToInt32(hdId.Text));
                        txtMyVideoTitle.Text = itm.MyVideoTitle;
                        ddlIsActive.SelectedValue = itm.IsActive ? "1" : "0";
                        rbPublic.Checked = itm.IsPublic;
                        rbMember.Checked = !itm.IsPublic;
                        ddlIsFitness.SelectedValue = itm.IsFitness ? "1" : "0";
                        
                        if (!string.IsNullOrEmpty(itm.MyVideoFileName))
                        {
                            fuMyVideoFileName.FileName = itm.MyVideoFileName;
                        }

                        if (!string.IsNullOrEmpty(itm.Poster))
                        {
                            fuPoster.Style.Add("display", "none");
                            pnlPoster.Visible = true;
                            lblPoster.Text = itm.Poster;
                            hdPoster.Value = "0";
                        }
                        else
                        {
                            pnlPoster.Visible = false;
                            hdPoster.Value = "1";
                        }

                        if (!string.IsNullOrEmpty(itm.HDQTFileName))
                        {
                            fuHDQTFileName.FileName = itm.HDQTFileName;
                        }

                        if (!string.IsNullOrEmpty(itm.HDWinFileName))
                        {
                            fuHDWinFileName.FileName = itm.HDWinFileName;
                        }

                        if (!string.IsNullOrEmpty(itm.LDQTFileName))
                        {
                            fuLDQTFileName.FileName = itm.LDQTFileName;
                        }

                        if (!string.IsNullOrEmpty(itm.LDWinFileName))
                        {
                            fuLDWinFileName.FileName = itm.LDWinFileName;
                        }
                    }
                }
                else
                {
                    lblDialogTitle.Text = "ADD NEW MY VIDEO";

                    txtMyVideoTitle.Text = "";
                    ddlIsActive.SelectedValue = "1";

                    rbPublic.Checked = false;
                    rbMember.Checked = true;
                    ddlIsFitness.SelectedValue = "0";
                    
                    fuPoster.Visible = true;
                    pnlPoster.Visible = false;
                }

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "$('#editDialog').dialog('open');", true);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            /*if (hdId.Text == "-1")
                if (!fuMyVideoFileName.HasFile)
                    return;*/
            
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                if (hdId.Text == "-1")
                {
                    MyVideo itm = new MyVideo();
                    
                    itm.MyVideoTitle = txtMyVideoTitle.Text;
                    itm.IsActive = ddlIsActive.SelectedValue == "1";
                    itm.IsFitness = ddlIsFitness.SelectedValue == "1";
                    itm.IsPublic = rbPublic.Checked;

                    itm.MyVideoFileName = fuMyVideoFileName.FileName;
                    itm.Poster = fuPoster.FileName;

                    itm.HDQTFileName = "";
                    itm.HDWinFileName = "";
                    itm.LDQTFileName = "";
                    itm.LDWinFileName = "";
                    if (rbMember.Checked)
                    {
                        itm.HDQTFileName = fuHDQTFileName.FileName;
                        itm.HDWinFileName = fuHDWinFileName.FileName;
                        itm.LDQTFileName = fuLDQTFileName.FileName;
                        itm.LDWinFileName = fuLDWinFileName.FileName;
                    }
                    repo.Insert(itm);

                    if (fuMyVideoFileName.HasFile)
                    {
                        string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/Preview"), itm.PhysFileName);
                        fuMyVideoFileName.SaveAs(filePath);
                    }
                    if (fuPoster.HasFile)
                    {
                        string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/Poster"), itm.PhysPoster);
                        fuPoster.SaveAs(filePath);
                    }

                    if (rbMember.Checked)
                    {
                        if (fuHDQTFileName.HasFile)
                        {
                            string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/HDQT"), itm.PhysHDQTFileName);
                            fuHDQTFileName.SaveAs(filePath);
                        }
                        if (fuHDWinFileName.HasFile)
                        {
                            string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/HDWin"), itm.PhysHDWinFileName);
                            fuHDWinFileName.SaveAs(filePath);
                        }
                        if (fuLDQTFileName.HasFile)
                        {
                            string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/LDQT"), itm.PhysLDQTFileName);
                            fuLDQTFileName.SaveAs(filePath);
                        }
                        if (fuLDWinFileName.HasFile)
                        {
                            string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/LDWin"), itm.PhysLDWinFileName);
                            fuLDWinFileName.SaveAs(filePath);
                        }
                    }
                }
                else
                {
                    MyVideo itm = repo.Find(Convert.ToInt32(hdId.Text));

                    itm.MyVideoTitle = txtMyVideoTitle.Text;
                    itm.IsActive = ddlIsActive.SelectedValue == "1";
                    itm.IsFitness = ddlIsFitness.SelectedValue == "1";
                    itm.IsPublic = rbPublic.Checked;

                    if (fuMyVideoFileName.IsNewFile)
                    {
                        DeleteMyVideoFile(itm.MyVideoId, "", "");
                        itm.MyVideoFileName = "";
                        if (fuMyVideoFileName.HasFile)
                        {
                            itm.MyVideoFileName = fuMyVideoFileName.FileName;
                            string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/Preview"), itm.PhysFileName);
                            fuMyVideoFileName.SaveAs(filePath);
                        }
                    }
                    if (hdPoster.Value == "1")
                    {
                        DeleteMyVideoFile(itm.MyVideoId, "poster", "");
                        itm.Poster = "";
                        if (fuPoster.HasFile)
                        {
                            itm.Poster = fuPoster.FileName;
                            string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/Poster"), itm.PhysPoster);
                            fuPoster.SaveAs(filePath);
                        }
                    }

                    if (rbPublic.Checked)
                    {
                        itm.HDQTFileName = "";
                        DeleteMyVideoFile(itm.MyVideoId, "hd", "qt");

                        itm.HDWinFileName = "";
                        DeleteMyVideoFile(itm.MyVideoId, "hd", "Win");

                        itm.LDQTFileName = "";
                        DeleteMyVideoFile(itm.MyVideoId, "ld", "qt");

                        itm.LDWinFileName = "";
                        DeleteMyVideoFile(itm.MyVideoId, "ld", "Win");
                    }
                    else
                    {
                        if (fuHDQTFileName.IsNewFile)
                        {
                            DeleteMyVideoFile(itm.MyVideoId, "hd", "qt");
                            itm.HDQTFileName = "";
                            if (fuHDQTFileName.HasFile)
                            {
                                itm.HDQTFileName = fuHDQTFileName.FileName;
                                string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/HDQT"), itm.PhysHDQTFileName);
                                fuHDQTFileName.SaveAs(filePath);
                            }
                        }
                        if (fuHDWinFileName.IsNewFile)
                        {
                            DeleteMyVideoFile(itm.MyVideoId, "hd", "Win");
                            itm.HDWinFileName = "";
                            if (fuHDWinFileName.HasFile)
                            {
                                itm.HDWinFileName = fuHDWinFileName.FileName;
                                string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/HDWin"), itm.PhysHDWinFileName);
                                fuHDWinFileName.SaveAs(filePath);
                            }
                        }
                        if (fuLDQTFileName.IsNewFile)
                        {
                            DeleteMyVideoFile(itm.MyVideoId, "ld", "qt");
                            itm.LDQTFileName = "";
                            if (fuLDQTFileName.HasFile)
                            {
                                itm.LDQTFileName = fuLDQTFileName.FileName;
                                string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/LDQT"), itm.PhysLDQTFileName);
                                fuLDQTFileName.SaveAs(filePath);
                            }
                        }
                        if (fuLDWinFileName.IsNewFile)
                        {
                            DeleteMyVideoFile(itm.MyVideoId, "ld", "Win");
                            itm.LDWinFileName = "";
                            if (fuLDWinFileName.HasFile)
                            {
                                itm.LDWinFileName = fuLDWinFileName.FileName;
                                string filePath = Path.Combine(Server.MapPath("~/Files/MyVideos/LDWin"), itm.PhysLDWinFileName);
                                fuLDWinFileName.SaveAs(filePath);
                            }
                        }
                    }
                    
                    repo.Update(itm);
                }
            }
            LoadMyVideo();
        }

        protected string GetFilePath(int id, string quality, string os)
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                MyVideo video = repo.Find(id);

                string basePath = Server.MapPath("~/Files/MyVideos/");

                if ((quality == "") && (os == ""))
                    return Path.Combine(basePath, "Preview", video.PhysFileName);

                if ((quality == "poster") && (os == ""))
                    return Path.Combine(basePath, "Poster", video.PhysPoster);

                if (quality == "hd")
                {
                    if (os == "qt")
                    {
                        return Path.Combine(basePath, "HDQT", video.PhysHDQTFileName);
                    }
                    else
                    {
                        return Path.Combine(basePath, "HDWin", video.PhysHDWinFileName);
                    }
                }
                else
                {
                    if (os == "qt")
                    {
                        return Path.Combine(basePath, "LDQT", video.PhysLDQTFileName);
                    }
                    else
                    {
                        return Path.Combine(basePath, "LDWin", video.PhysLDWinFileName);
                    }
                }
            }
        }

        protected void DeleteMyVideoFile(int id, string quality, string os)
        {
            string path = GetFilePath(id, quality, os);
            if (File.Exists(path))
                try
                {
                    File.Delete(path);
                }
                catch (Exception ex) { }
        }

        protected void DeleteMyVideo(int id)
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                MyVideo itm = repo.Find(id);
                if (itm != null)
                {
                    DeleteMyVideoFile(id, "", "");
                    DeleteMyVideoFile(id, "poster", "");
                    DeleteMyVideoFile(id, "hd", "win");
                    DeleteMyVideoFile(id, "hd", "qt");
                    DeleteMyVideoFile(id, "ld", "win");
                    DeleteMyVideoFile(id, "ld", "qt");

                    repo.Delete(id);
                }
            }
        }

        protected void CopyToRecentScene(int id)
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                MyVideo itm = repo.Find(id);
                if (itm != null)
                {
                    string pathMyVideo = Path.Combine(Server.MapPath("~/Files/MyVideos"), itm.PhysFileName);
                    if (File.Exists(pathMyVideo))
                    {
                        RecentScene rs = new RecentScene();
                        rs.RecentSceneTitle = itm.MyVideoTitle;
                        rs.RecentSceneFileName = itm.MyVideoFileName;
                        rs.IsActive = itm.IsActive;

                        using (var repoRS = RepositoryFactory.ResolveRepository<RecentSceneRepository>())
                        {
                            repoRS.Insert(rs);
                            string pathRS = Path.Combine(Server.MapPath("~/Files/RecentScenes"), rs.PhysFileName);
                            File.Copy(pathMyVideo, pathRS);
                        }
                    }
                }
            }
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                foreach (int id in Selected)
                {
                    DeleteMyVideo(id);
                }
            }

            LoadMyVideo();
        }

        protected void btnActivateSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                foreach (int id in Selected)
                {
                    repo.Activate(id);
                }
            }

            LoadMyVideo();
        }

        protected void btnDeactivateSelected_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
            {
                foreach (int id in Selected)
                {
                    repo.Deactivate(id);
                }
            }

            LoadMyVideo();
        }

        protected void btnReverseSelected_Click(object sender, EventArgs e)
        {
            var otherScenes = new List<int>();

            foreach (var scene in MyVideoList())
            {
                if (!Selected.Contains(scene.MyVideoId))
                {
                    otherScenes.Add(scene.MyVideoId);
                }
            }

            Selected = otherScenes.ToArray();
            LoadMyVideo();
        }

        protected void btnCopyToHomeSelected_Click(object sender, EventArgs e)
        {
            foreach (int id in Selected)
            {
                CopyToRecentScene(id);
            }

            LoadMyVideo();
            JsCodeToRunOnReady = "alert('Copy successfuly!')";
        }
        
        protected void chbAll_CheckChanged(Object sender, EventArgs e)
        {
            bool chk = (sender as CheckBox).Checked;
            if (chk)
            {
                var other = new List<int>();
                using (var repo = RepositoryFactory.ResolveRepository<MyVideoRepository>())
                {
                    foreach (var scene in repo.FindAll())
                        other.Add(scene.MyVideoId);
                }

                Selected = other.ToArray();
            }
            else
                Selected = new int[] { };

            LoadMyVideo();
        }
    }
}